import ajax from '../../ajax'
import changeProps from '../changeProps'
import { mixinAfterReqData } from '../mixins'
import { isJSON } from '../../utils'

export default function(Route){

  let request = Route.afterRequest
  const errorBack = typeof request.errorBack !== 'boolean' ? true : request.errorBack
  request = request.request

  if(!isJSON(request) && !(request instanceof Array))
    return false
  if(isJSON(request))
    request = [request]

  const component = Route.component
  const beforeRouteEnter = component.beforeRouteEnter
  const mixins = component.mixins || []
  const props = Route.props
  const requestData = {
    afterRequestLoading: false,
    afterRequestStatus: false,
    requestData: {}
  }
  const data = {
    after: requestData
  }
  let vm
  let requestLength = 0
  let successSize = 0
  let errorSize = 0


  const SUCCESS = () => {
    $loading.hide().then(() => {
      vm.data.after.afterRequestLoading = true
      if(requestLength > successSize){
        $toast.show('接口请求失败', 1000).then(() => {
          if(false !== errorBack)
            $router.back('/')
        })
        return false
      }
      vm.data.after.afterRequestStatus = true
    })
  }

  const Request = (must, err, success, name, data) => {
    if(must){
      successSize += success
      errorSize += err
    }
    requestData.requestData[name] = data
    if(requestLength === successSize + errorSize)
      SUCCESS()
  }

  const afterRequest = function(to, from, next){

    requestData.afterRequestLoading = false
    requestData.afterRequestStatus = false
    requestData.requestData = {}

    requestLength = 0
    successSize = 0
    errorSize = 0

    vm = undefined

    for(let i = 0; i < request.length; i++){

      const name = request[i].name
      const url = request[i].url
      const type = request[i].type || 'get'
      const data = request[i].data
      const response = request[i].response
      const must = request[i].must || false

      if(typeof url !== 'string' || typeof name !== 'string')
        continue

      if(must)
        requestLength += 1

      ajax({
        url,
        type,
        data
      })
      .then(function(res){
        Request(must, 0, 1, name, res.data)
      })
      .catch(function(err){
        Request(must, 1, 0, name, err)
      })

    }

    if(requestLength > successSize + errorSize)
      $loading.show('拼命加载中..')

    next( $vm => {
      vm = $vm
    })
  }
  component.mixins = mixinAfterReqData(mixins, data)

  component.beforeRouteEnter = function(to, from, next){
    if(typeof beforeRouteEnter === 'function')
      return beforeRouteEnter(to, from, function(status){
        if(status !== undefined)
          return next(status)

        afterRequest(to, from, next)
      })

    afterRequest(to, from, next)
  }

}
